#include "mylib.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>  
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>


myFILE* my_fopen(const char* path, const char* mode)
{
  int flags = 0;
  if(strcmp(mode, "r") == 0)
  {
    flags |= O_RDONLY;
  }
  else if(strcmp(mode, "w") == 0)
  {
    flags |= (O_CREAT|O_WRONLY|O_TRUNC);
  }
  else if(strcmp(mode, "a") == 0)
  {
    flags |= (O_CREAT|O_WRONLY|O_APPEND);
  }
  else
  {

  }

  int fd = 0;
  if(flags & O_RDONLY)
    fd = open(path, flags);
  else
  {
    fd = open(path, flags, 0666);
  }

  if(fd < 0)
  {
    errno = 2;
    return NULL;
  }

  myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
  if(fp == NULL)
  {
    errno = 3;
    return NULL;
  }
  fp->_end = 0;
  fp->_fileno = fd;

  return fp;
}

int my_fputs(const char* s, myFILE* stream)
{
  memcpy(stream->_buffer + stream->_end, s, strlen(s));
  stream->_end += strlen(s);

  if(stream->_buffer[stream->_end - 1] == '\n')
  {
    my_fflush(stream);
  }

  return strlen(s);
}

int my_fflush(myFILE* stream)
{
  if(stream->_end > 0);
    write(stream->_fileno, stream->_buffer, stream->_end);

  stream->_end = 0;

  return 1;
}

int my_fclose(myFILE* fp)
{
  my_fflush(fp);
  close(fp->_fileno);
  return fp->_fileno;
}

